package io.renren.modules.reception.controller;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.FastIDUtil;
import io.renren.modules.member.entity.TStoreMemberAccountDetailEntity;
import io.renren.modules.member.entity.TStoreMemberConsumeRecordEntity;
import io.renren.modules.member.entity.TStoreMemberEntity;
import io.renren.modules.member.service.TStoreMemberAccountDetailService;
import io.renren.modules.member.service.TStoreMemberConsumeRecordService;
import io.renren.modules.member.service.TStoreMemberRuleService;
import io.renren.modules.member.service.TStoreMemberService;
import io.renren.modules.reception.entity.TStoreFastfoodRecordEntity;
import io.renren.modules.reception.entity.vo.PayVo;
import io.renren.modules.reception.entity.vo.TakeoutInfo;
import io.renren.modules.store.entity.TStoreAccountListEntity;
import io.renren.modules.store.entity.TStoreAccountUnitEntity;
import io.renren.modules.store.entity.TStoreBrandEntity;
import io.renren.modules.store.entity.TStoreStaffEntity;
import io.renren.modules.store.service.TStoreAccountListService;
import io.renren.modules.store.service.TStoreAccountUnitService;
import io.renren.modules.store.service.TStoreStaffService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.reception.entity.TStoreTakeoutRecordEntity;
import io.renren.modules.reception.service.TStoreTakeoutRecordService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-03-02 13:26:00
 */
@RestController
@RequestMapping("reception/tstoretakeoutrecord")
public class TStoreTakeoutRecordController extends AbstractController {
    @Autowired
    private TStoreTakeoutRecordService tStoreTakeoutRecordService;
    @Autowired
    private TStoreStaffService storeStaffService;
    @Autowired
    private TStoreAccountUnitService storeAccountUnitService;
    @Autowired
    private TStoreMemberService storeMemberService;
    @Autowired
    private TStoreMemberAccountDetailService storeMemberAccountDetailService;
    @Autowired
    private TStoreAccountUnitService accountUnitService;
    @Autowired
    private TStoreMemberRuleService memberRuleService;
    @Autowired
    private TStoreMemberConsumeRecordService consumeRecordService;
    @Autowired
    private TStoreAccountListService storeAccountListService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("reception:tstoreorderrecord:list")
    public R list(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        PageUtils page = tStoreTakeoutRecordService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listTakeout")
    @RequiresPermissions("reception:tstoreorderrecord:list")
    public R listTakeout(@RequestParam Map<String, Object> params){
        params.put("sellerId",getSeller());
        Page<TStoreTakeoutRecordEntity> page = tStoreTakeoutRecordService.listTakeout(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("reception:tstoreorderrecord:info")
    public R info(@PathVariable("id") Long id){
		TStoreTakeoutRecordEntity tStoreTakeoutRecord = tStoreTakeoutRecordService.getById(id);

        return R.ok().put("tStoreTakeoutRecord", tStoreTakeoutRecord);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("reception:tstoreorderrecord:save")
    public R save(@RequestBody TakeoutInfo takeoutInfo){
        takeoutInfo.getTakeoutInfo().setTime(new Date());
        //保存账单（未付款）
        if (takeoutInfo.getTakeoutInfo().getPaySign() == 1){
            takeoutInfo.getTakeoutInfo().setSellerId(getSeller());
            takeoutInfo.getTakeoutInfo().setTakeoutId(FastIDUtil.fastId());
            takeoutInfo.getTakeoutInfo().setStatus(1);
        }
        //结账
        else {
            //直接结账（保存账单后的结账则不用）
            if (takeoutInfo.getTakeoutInfo().getDirectPayFlag()){
                takeoutInfo.getTakeoutInfo().setSellerId(getSeller());
                takeoutInfo.getTakeoutInfo().setTakeoutId(FastIDUtil.fastId());
                takeoutInfo.getTakeoutInfo().setStatus(3);
            }else {
                takeoutInfo.getTakeoutInfo().setSellerId(getSeller());
                takeoutInfo.getTakeoutInfo().setTakeoutId(FastIDUtil.fastId());
                takeoutInfo.getTakeoutInfo().setStatus(1);
            }

        }
        if (takeoutInfo.getTakeoutInfo().getFoodVos().size() == 0) {
            takeoutInfo.getTakeoutInfo().setFoodVo(takeoutInfo.getTakeoutInfo().getFoodVo());
        } else {
            Object json = JSONObject.toJSON(takeoutInfo.getTakeoutInfo().getFoodVos());
            takeoutInfo.getTakeoutInfo().setFoodVo(json.toString());
        }
        tStoreTakeoutRecordService.saveOrUpdate(takeoutInfo.getTakeoutInfo());

        //挂账单位
        if (takeoutInfo.getTakeoutInfo().getAccountId() != null){
            Map<String,Object> map = new HashMap<>();
            map.put("accountId",takeoutInfo.getTakeoutInfo().getAccountId());
            map.put("sellerId",getSeller());
            map.put("money",takeoutInfo.getTakeoutInfo().getReallyGet());
            accountUnitService.updateAccount(map);

            TStoreAccountListEntity storeAccountListEntity = new TStoreAccountListEntity();
            storeAccountListEntity.setAccountId(takeoutInfo.getTakeoutInfo().getAccountId())
                    .setOrderId(takeoutInfo.getTakeoutInfo().getTakeoutId())
                    .setMoney(takeoutInfo.getTakeoutInfo().getTotalMoney())
                    .setCreateTime(new Date())
                    .setCreateUser(getUser().getUsername())
                    .setFoodVo(JSONObject.toJSON(takeoutInfo.getTakeoutInfo().getFoodVos()).toString())
                    .setStatus(1)
                    .setType(1);
            storeAccountListService.save(storeAccountListEntity);
        }

        if (takeoutInfo.getTakeoutInfo().getMemberId() != null){
            //更新会员账户会员
            double exchangeIntegral = memberRuleService.ExchangeIntegral(getSeller(), takeoutInfo.getTakeoutInfo().getMemberTypeId());
            Map<String, Object> map = new HashMap<>();
            TStoreMemberConsumeRecordEntity consumeRecordEntity = new TStoreMemberConsumeRecordEntity();
            List<PayVo> list = takeoutInfo.getTakeoutInfo().getPayVo();
            for (int i = 0 ; i < list.size() ;i++){
                if (list.get(i).getPayMethodName().equals("储值卡")){
                    double memberIntegral = Math.ceil(list.get(i).getPayMoney()*exchangeIntegral);
                    map.put("integral",memberIntegral);
                    map.put("amount",list.get(i).getPayMoney());
                    consumeRecordEntity.setConsumeAmout(list.get(i).getPayMoney());
                    map.put("memberId",takeoutInfo.getTakeoutInfo().getMemberId());
                    storeMemberAccountDetailService.updateMemberAccountConsume(map);

                    //插入会员消费记录表
                    consumeRecordEntity.setCreateTime(new Date());
                    consumeRecordEntity.setCreateUserId(getUserId());
                    consumeRecordEntity.setMemberId(takeoutInfo.getTakeoutInfo().getMemberId());
                    consumeRecordEntity.setOrderId(Long.parseLong(takeoutInfo.getTakeoutInfo().getTakeoutId()));
                    consumeRecordEntity.setRemark(takeoutInfo.getTakeoutInfo().getRemark());
                    consumeRecordEntity.setSellerId(getSeller());
                    consumeRecordEntity.setDiscount(takeoutInfo.getTakeoutInfo().getDiscount());
                    consumeRecordService.save(consumeRecordEntity);
                }

            }

        }

        TStoreTakeoutRecordEntity foodInfo = tStoreTakeoutRecordService.getOne(new QueryWrapper<TStoreTakeoutRecordEntity>()
                .eq("takeout_id", takeoutInfo.getTakeoutInfo().getTakeoutId())
        );

        TStoreStaffEntity staffEntity = storeStaffService.getOne(new QueryWrapper<TStoreStaffEntity>()
                .eq("staff_id", foodInfo.getStaffId())
        );
        foodInfo.setStaffName(staffEntity.getStaffName());

        return R.ok().put("foodInfo", foodInfo);
    }

    /**
     * 开始配送
     */
    @RequestMapping("/startTrans")
    public R startTrans(@RequestBody TakeoutInfo takeoutInfo){
        TStoreTakeoutRecordEntity recordEntity = new TStoreTakeoutRecordEntity();
        recordEntity.setStatus(2);
        recordEntity.setId(takeoutInfo.getTakeoutInfo().getId());
        tStoreTakeoutRecordService.updateById(recordEntity);
        Map<String,Object> map = new HashMap<>();
        if (takeoutInfo.getTakeoutInfo().getAccountId() != null){
            TStoreAccountUnitEntity unitEntity = storeAccountUnitService.getById(takeoutInfo.getTakeoutInfo().getAccountId());
            map.put("unitInfo",unitEntity);
        }else {
            map.put("unitInfo",null);
        }
        if (takeoutInfo.getTakeoutInfo().getMemberId() != null){
            TStoreMemberEntity memberEntity = storeMemberService.getById(takeoutInfo.getTakeoutInfo().getMemberId());
            TStoreMemberAccountDetailEntity accountDetailEntity = storeMemberAccountDetailService.getById(takeoutInfo.getTakeoutInfo().getMemberId());
            map.put("memberInfo",memberEntity);
            map.put("memberAccountDetailInfo",accountDetailEntity);
        }else {
            map.put("memberInfo",null);
            map.put("memberAccountDetailInfo",null);
        }
        return R.ok().put("info",map);
    }

    /**
     * 结束配送
     */
    @RequestMapping("/endTrans")
    public R endTrans(@RequestBody TakeoutInfo takeoutInfo){
        TStoreTakeoutRecordEntity recordEntity = new TStoreTakeoutRecordEntity();
        recordEntity.setStatus(3);
        recordEntity.setId(takeoutInfo.getTakeoutInfo().getId());
        tStoreTakeoutRecordService.updateById(recordEntity);
        return R.ok();
    }

    /**
     * 结账
     */
    @RequestMapping("/CheckOut")
    public R CheckOut(@RequestBody TakeoutInfo takeoutInfo){
        takeoutInfo.getTakeoutInfo().setStatus(3);
        takeoutInfo.getTakeoutInfo().setFoodVo(takeoutInfo.getTakeoutInfo().getFoodVo());
        tStoreTakeoutRecordService.updateById(takeoutInfo.getTakeoutInfo());
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("reception:tstoretakeoutrecord:update")
    public R update(@RequestBody TStoreTakeoutRecordEntity tStoreTakeoutRecord){
		tStoreTakeoutRecordService.updateById(tStoreTakeoutRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("reception:tstoretakeoutrecord:delete")
    public R delete(@RequestBody Long[] ids){
		tStoreTakeoutRecordService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
